using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input; // 添加此 using 以使用 RelayCommand
using CANBusTools.ViewModels;

namespace CANBusTools.ViewModels
{
    public class CanGuiViewModel : ViewModelBase
    {
        // CAN 总线相关对象，替换为实际类型
        private object _canBus = new object();
        private object? _busHelper;

        public string Port { get; set; } = "COM14";
        public string DbcPath { get; set; } = string.Empty;

        public ObservableCollection<ViewModelBase> ControlSections { get; }

        public ICommand ConnectCommand { get; }
        public ICommand ExitCommand { get; }
        public ICommand BrowseDbcCommand { get; }

        public CanGuiViewModel()
        {
            ControlSections = new ObservableCollection<ViewModelBase>();

            // 初始化各个控制模块 ViewModel，busHelper 传入后替换为实际对象
            _busHelper = new object();

            ConnectCommand = new RelayCommand(ConnectCanBus);
            ExitCommand = new RelayCommand(ExitApplication);
            BrowseDbcCommand = new RelayCommand(BrowseDbcFile);

            ControlSections.Add(new GearControlViewModel(_busHelper));
            ControlSections.Add(new SpeedControlViewModel(_busHelper));
            ControlSections.Add(new RadarControlViewModel(_busHelper));
            ControlSections.Add(new LightControlViewModel(_busHelper));
            ControlSections.Add(new IgnitionControlViewModel(_busHelper));
            ControlSections.Add(new WarningControlViewModel(_busHelper));
            ControlSections.Add(new RctaControlViewModel(_busHelper));
            ControlSections.Add(new DoorControlViewModel(_busHelper));
            ControlSections.Add(new SteerControlViewModel(_busHelper));
        }

        private void ConnectCanBus()
        {
            try
            {
                // 这里示例伪代码，替换为实际 CAN 总线初始化逻辑
                if (string.IsNullOrWhiteSpace(Port))
                    throw new ArgumentException("COM 端口不能为空");
                if (string.IsNullOrWhiteSpace(DbcPath))
                    throw new ArgumentException("DBC 文件路径不能为空");
                if (!System.IO.File.Exists(DbcPath))
                    throw new System.IO.FileNotFoundException("DBC 文件不存在");

                // TODO: 替换为实际 CAN 总线初始化代码
                _canBus = new object(); // 伪代码，替换为实际初始化
                _busHelper = new object(); // 伪代码，替换为实际初始化

                // 更新各控制模块的 busHelper 引用
                foreach (var section in ControlSections)
                {
                    var prop = section.GetType().GetField("_busHelper", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    if (prop != null)
                    {
                        prop.SetValue(section, _busHelper);
                    }
                }

                Console.WriteLine($"成功连接 CAN 总线，端口: {Port}, DBC: {DbcPath}");
            }
            catch (Exception ex)
            {
                // TODO: 弹窗提示错误，示例用 Console.WriteLine
                Console.WriteLine($"CAN 初始化失败: {ex.Message}");
            }
        }

        private void ExitApplication()
        {
            try
            {
                // TODO: 实现总线关闭和应用退出逻辑
                Console.WriteLine("Exiting application");
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"退出失败: {ex.Message}");
            }
        }

        private async void BrowseDbcFile()
        {
            try
            {
                var window = Avalonia.Application.Current.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop
                    ? desktop.MainWindow
                    : null;
                
                if (window != null)
                {
                    var files = await window.StorageProvider.OpenFilePickerAsync(new Avalonia.Platform.Storage.FilePickerOpenOptions
                    {
                        Title = "Select DBC File",
                        AllowMultiple = false,
                        FileTypeFilter = new[]
                        {
                            new Avalonia.Platform.Storage.FilePickerFileType("DBC files")
                            {
                                Patterns = new[] { "*.dbc" }
                            }
                        }
                    });
                    
                    if (files.Count > 0)
                    {
                        DbcPath = files[0].Path.LocalPath ?? string.Empty;
                        OnPropertyChanged(nameof(DbcPath));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"选择 DBC 文件失败: {ex.Message}");
            }
        }
    }
}
